package com.ruoyi.web.controller.system;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.Response;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.cs.domain.TUser;
import com.ruoyi.cs.domain.TVipGrade;
import com.ruoyi.cs.mapper.TUserMapper;
import com.ruoyi.cs.mapper.TVipGradeMapper;
import com.ruoyi.framework.web.service.TokenService;
import io.swagger.annotations.ApiOperation;
import org.checkerframework.checker.guieffect.qual.AlwaysSafe;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.service.ISysDictDataService;
import com.ruoyi.system.service.ISysDictTypeService;

/**
 * 数据字典信息
 * 
 * @author ruoyi
 */
@RestController
@RequestMapping("/system/dict/data")
@SuppressWarnings("all")
public class SysDictDataController extends BaseController
{
    @Autowired
    private ISysDictDataService dictDataService;
    @Autowired
    private ISysDictTypeService dictTypeService;
    @Autowired
    private TokenService tokenService;
    @Autowired
    private TUserMapper tUserMapper;
    @Autowired
    private TVipGradeMapper tVipGradeMapper;

    @PreAuthorize("@ss.hasPermi('system:dict:list')")
    @RequestMapping(value="list",method = RequestMethod.POST)
    public TableDataInfo list(@RequestBody  SysDictData dictData)
    {
        startPage(dictData.getPageNum(),dictData.getPageSize());
        List<SysDictData> list = dictDataService.selectDictDataList(dictData);
        return getDataTable(list);
    }

//    @Log(title = "字典数据", businessType = BusinessType.EXPORT)
//    @PreAuthorize("@ss.hasPermi('system:dict:export')")
//    @GetMapping("/export")
//    public AjaxResult export(SysDictData dictData)
//    {
//        List<SysDictData> list = dictDataService.selectDictDataList(dictData);
//        ExcelUtil<SysDictData> util = new ExcelUtil<SysDictData>(SysDictData.class);
//        return util.exportExcel(list, "字典数据");
//    }

//    /**
//     * 查询字典数据详细
//     */
//    @PreAuthorize("@ss.hasPermi('system:dict:query')")
//    @GetMapping(value = "/{dictCode}")
//    public AjaxResult getInfo(@PathVariable Long dictCode)
//    {
//        return AjaxResult.success(dictDataService.selectDictDataById(dictCode));
//    }

    /**
     * 根据字典类型查询字典数据信息
     */
    @GetMapping(value = "/type/{dictType}")
    public AjaxResult dictType(@PathVariable String dictType)
    {
        List<SysDictData> data = dictTypeService.selectDictDataByType(dictType);
        if (StringUtils.isNull(data))
        {
            data = new ArrayList<SysDictData>();
        }
        return AjaxResult.success(data);
    }

    /**
     * 新增字典类型
     */
    @PreAuthorize("@ss.hasPermi('system:dict:add')")
    @Log(title = "字典数据", businessType = BusinessType.INSERT)
    @RequestMapping(value="add",method = RequestMethod.POST)
    public AjaxResult add(@RequestBody SysDictData dict)
    {
        dict.setCreateBy(SecurityUtils.getUsername());
        return dictDataService.insertDictData(dict);
    }

    /**
     * 修改保存字典类型
     */
    @PreAuthorize("@ss.hasPermi('system:dict:edit')")
    @Log(title = "字典数据", businessType = BusinessType.UPDATE)
    @RequestMapping(value="edit",method = RequestMethod.POST)
    public AjaxResult edit(@RequestBody SysDictData dict)
    {
        dict.setUpdateBy(SecurityUtils.getUsername());
        return dictDataService.updateDictData(dict);
    }

    /**
     * 删除字典类型
     */
    @PreAuthorize("@ss.hasPermi('system:dict:remove')")
    @Log(title = "字典类型", businessType = BusinessType.DELETE)
    @RequestMapping(value="remove",method = RequestMethod.GET)
    public AjaxResult remove(String dictCodes)
    {
        if (StringUtils.isNotEmpty(dictCodes)){
            String[] ids = dictCodes.split(",");
            return toAjax(dictDataService.deleteDictDataByIds(ids));
        }else {
            return new AjaxResult(Constants.FAILCODE,"参数不能为空！");
        }

    }

    @GetMapping(value = "common/type/{dictType}")
    public AjaxResult commonDictType(@PathVariable String dictType)
    {
        List<SysDictData> data = dictTypeService.selectDictDataByType(dictType);
        if (StringUtils.isNull(data))
        {
            data = new ArrayList<SysDictData>();
        }
        return AjaxResult.success(data);
    }


    @GetMapping(value = "common/commonCZDictType")
    public AjaxResult commonDictType()
    {
        String dictType = "first_recharge_give_ratio";
        String type = "0";
        long vip = 0;
        BigDecimal ratio = BigDecimal.valueOf(0);
        LoginUser loginUser = tokenService.getLoginUserWeb(ServletUtils.getRequest());
        if (loginUser != null){
            SysUser user = loginUser.getUser();
            if (user != null){
                String userId = user.getLoginUserId();
                TUser tUser = tUserMapper.selectTUserById(userId);
                if (tUser.getUserTotalRecharge().compareTo(new BigDecimal("0")) > 0){
//                    dictType = "recharge_give";
                    type = "1";
                    vip = tUser.getUserVip();
                    if(vip > 0){
                        TVipGrade tVipGrade = tVipGradeMapper.getUserVip(vip);
                        ratio =  tVipGrade.getGiveRatio();
                    }
                }
            }
        }
        List<SysDictData> data = dictTypeService.selectDictDataByType(dictType);
        if(data.size()>0 && type.equals("1")){
            /**VIP充值赠送*/
            for (SysDictData datum : data) {
                datum.setDictValue(ratio.toString());
            }
        }

        Map map = new HashMap();
        map.put("type",type);
        map.put("list",data);
        map.put("vip",vip);
        return AjaxResult.success(map);
    }
}
